<?php


namespace app\store\model\lottery;

use app\common\model\lottery\Goods as LotteryGoodsModel;
use app\store\model\Coupon;
use app\store\model\UploadFile;
use app\store\model\Goods as GoodsModel;

class Goods extends LotteryGoodsModel
{

    public function getTypeAttr($value)
    {
        $text = ['1' => '未中奖', '2' => '积分', '3' => '优惠券', '4' => '赠品'];
        return ['text' => $value, 'value' => $text[$value]];
    }

    public static function getGoodsByLotteryId($lottery_id)
    {
        return self::with('logo')->where('lottery_id', $lottery_id)->order('sort asc')->select()->toArray();
    }



    public static function getList($lottery_id)
    {
        $lotteries = self::getGoodsByLotteryId($lottery_id);
        array_walk($lotteries, function (&$val) {
            $val['prize'] = self::reversePrize($val['type']['text'], $val['prize']);
        });
        return $lotteries;
    }

    private static function reversePrize($type, $prize)
    {
        switch ($type) {
            //优惠券
            case 3:
                $prize = Coupon::find($prize);
                break;
            //赠品
            case 4:
                $prize = GoodsModel::with('image.file')->find($prize);
                break;
        }
        return $prize;
    }
    public function add(array $data)
    {
        $data['wxapp_id'] = static::$wxapp_id;
        return $this->allowField(true)->save($data);
    }

    public static function detail($id)
    {
        $lottry = self::with('logo')->find($id);
        $lottry['prize'] = self::reversePrize($lottry['type']['text'], $lottry['prize']);
        return $lottry;
    }

    public function edit(array $data)
    {
        return $this->allowField(true)->save($data);
    }
}